package yiling

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/go-pay/gopay"
)

// CodePay 条形码支付接口 https://console-docs.apipost.cn/preview/bac9c0392acc5481/d99904ea1794591d?target_id=c7c6abac-83e5-44bb-aab1-9f6d7e0f0a14
func (c *Client) CodePay(ctx context.Context, bm gopay.BodyMap) (rsp *RspPay, err error) {
	err = bm.CheckEmptyError("cashierNum", "terminalUniqueNo", "orderNumExternal", "dynamicId", "inputFee")
	if err != nil {
		return nil, err
	}
	bm.Set("service", ServiceCreateAndPay)
	var bs []byte
	if bs, err = c.doPost(ctx, bm); err != nil {
		return nil, err
	}
	rsp = new(RspPay)
	if err = json.Unmarshal(bs, rsp); err != nil {
		return nil, fmt.Errorf("[%w], bytes: %s", gopay.UnmarshalErr, string(bs))
	}
	if err := bizErrCheck(rsp.RspBase); err != nil {
		return nil, err
	}
	return rsp, nil
}

// Query 支付查询接口 https://console-docs.apipost.cn/preview/bac9c0392acc5481/d99904ea1794591d?target_id=c7c6abac-83e5-44bb-aab1-9f6d7e0f0a14
func (c *Client) Query(ctx context.Context, bm gopay.BodyMap) (rsp *RspPay, err error) {
	bm.Set("service", ServiceQuery)
	var bs []byte
	if bs, err = c.doPost(ctx, bm); err != nil {
		return nil, err
	}
	rsp = new(RspPay)
	if err = json.Unmarshal(bs, rsp); err != nil {
		return nil, fmt.Errorf("[%w], bytes: %s", gopay.UnmarshalErr, string(bs))
	}
	if err := bizErrCheck(rsp.RspBase); err != nil {
		return nil, err
	}
	return rsp, nil
}

// Refund  退款接口 https://console-docs.apipost.cn/preview/bac9c0392acc5481/d99904ea1794591d?target_id=c7c6abac-83e5-44bb-aab1-9f6d7e0f0a14
func (c *Client) Refund(ctx context.Context, bm gopay.BodyMap) (rsp *RspPay, err error) {
	err = bm.CheckEmptyError("cashierNum", "terminalUniqueNo", "refundFee", "refundExternalNum")
	if err != nil {
		return nil, err
	}
	bm.Set("clientType", "PC")
	bm.Set("service", ServiceRefund)
	var bs []byte
	if bs, err = c.doPost(ctx, bm); err != nil {
		return nil, err
	}
	rsp = new(RspPay)
	if err = json.Unmarshal(bs, rsp); err != nil {
		return nil, fmt.Errorf("[%w], bytes: %s", gopay.UnmarshalErr, string(bs))
	}
	if err := bizErrCheck(rsp.RspBase); err != nil {
		return nil, err
	}
	return rsp, nil
}

// RefundQuery 退款查询接口 https://console-docs.apipost.cn/preview/bac9c0392acc5481/d99904ea1794591d?target_id=c7c6abac-83e5-44bb-aab1-9f6d7e0f0a14
func (c *Client) RefundQuery(ctx context.Context, bm gopay.BodyMap) (rsp *RspPay, err error) {
	bm.Set("service", ServiceRefundQuery)
	var bs []byte
	if bs, err = c.doPost(ctx, bm); err != nil {
		return nil, err
	}
	rsp = new(RspPay)
	if err = json.Unmarshal(bs, rsp); err != nil {
		return nil, fmt.Errorf("[%w], bytes: %s", gopay.UnmarshalErr, string(bs))
	}
	if err := bizErrCheck(rsp.RspBase); err != nil {
		return nil, err
	}
	return rsp, nil
}
